import sys
import time

from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtWidgets import (QApplication, QWidget)
from PyQt5.QtCore import *
from system_hotkey import SystemHotkey

from 窗口设计.谷歌翻译主窗口UI import Ui_Form

import json
import requests
import urllib3

urllib3.disable_warnings() #消除http未验证SSL证书的警告

class TranslateThread(QThread):
    translate_result = pyqtSignal(str)

    def __init__(self,Engine):
        super(TranslateThread, self).__init__()
        self.engine = Engine
        self.finesh_translate = False
        self.req = requests.get

        ## init
        self.words = ' '
        self.source = 'en'
        self.target = 'zh-CN'

    def set_words(self,words):
        self.words = words
        self.translate_words()

    def set_source(self,source):
        if source == '中文':
            self.source = 'zh-CN'
        elif source == 'English':
            self.source = 'en'

        print (self.source)

    def set_target(self,target):
        if target == '中文':
            self.target = 'zh-CN'
        elif target == 'English':
            self.target = 'en'

        print(self.target)

    def translate_words(self):
        '''
        :param words: 要翻译的文字
        :param source: 源语言
        :param target: 目标语言
        :return: json url
        '''
        self.url = f"https://translate.googleapis.com/translate_a/single?client=gtx&sl={self.source}&tl={self.target}&dt=t&q='{self.words}'&ie=UTF-8&oe=UTF-8"
        self.finesh_translate = False

    def get_result(self):
        try:
            self.translate_words()
            print (self.url)
            res_json = self.req(self.url, verify=False).json()
            text = ''
            for i in res_json[0]:
                text += i[0]
            print (res_json)
            self.translate_result.emit(text)
        except:
            self.translate_result.emit('出现了某些不可描述的错误。')

    def run(self):
        while True:
            while self.finesh_translate == False:
                self.get_result()
                self.url = ''
                self.finesh_translate = True
            time.sleep(0.1)


class HotKeyThread(QThread,SystemHotkey):
    trigger = pyqtSignal()
    clipboard_message = pyqtSignal(str)
    def __init__(self,UI):
        self.ui = UI
        super(HotKeyThread,self).__init__()
        # control
        self.register(('shift', 'v'), callback=lambda x: self.start())
        self.trigger.connect(self.hotKeyEvent)

    def run(self):
        self.trigger.emit()

    def hotKeyEvent(self):
        if self.ui.windowState() == Qt.WindowMinimized:
            self.ui.showNormal()
        self.ui.raise_()
        self.ui.activateWindow()
        self.get_clipboard()


    def quitThread(self):
        if self.isRunning():
            self.quit()

    def get_clipboard(self):
        clipboard = QApplication.clipboard()
        try:
            if isinstance(clipboard.text(), str):
                self.clipboard_message.emit(clipboard.text())
        except:
            pass



class Mainwindow(QWidget,Ui_Form):
    def __init__(self):
        super(Mainwindow, self).__init__()
        self.now = time.time()

        self.setupUi(self)
        self.setWindowTitle('Google Translate- auther:luosaidage@139.com')
        self.hotkeythread = HotKeyThread(self)
        self.hotkeythread.clipboard_message.connect(self.paste_text)

        self.trans = TranslateThread('Google')
        self.trans.translate_result.connect(self.show_to_box)
        self.trans.start()

        self.lineEdit.setPlaceholderText(" 输入文字或粘贴文字")
        self.lineEdit.textChanged.connect(self.trans_wods)

        # 设置语言
        self.comboBox.currentIndexChanged.connect(self.set_source_language)
        self.comboBox_2.currentIndexChanged.connect(self.set_destnation_laguage)

    def set_source_language(self):
        self.trans.set_source(self.comboBox.currentText())

    def set_destnation_laguage(self):
        self.trans.set_source(self.comboBox_2.currentText())

    def paste_text(self,info):
        self.lineEdit.setText(info)
        self.trans_wods()

    def trans_wods(self):
        words = self.lineEdit.text()
        self.trans.set_words(words)

    def show_to_box(self,message):
        print (message)
        self.textBrowser_2.setText(message.strip('\''))



if __name__ == "__main__":
    if hasattr(Qt, 'AA_EnableHighDpiScaling'):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    if hasattr(Qt, 'AA_UseHighDpiPixmaps'):
        QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)

    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon('google_translate.ico'))
    form = Mainwindow()
    form.show()
    sys.exit(app.exec_())

